import axios from "axios";
import type { AxiosRequestConfig, AxiosResponse } from "axios";
import { useCommonStore } from "@/stores/common";
const commonStore = useCommonStore();
let baseURL = "/api";
if (process.env.NODE_ENV === "production") {
  baseURL = "http://192.168.0.226:9999/api";
}
axios.defaults.headers["Content-Type"] = "application/json;charset=utf-8";
const instance = axios.create({
  baseURL: baseURL,
  timeout: 5000,
});

instance.interceptors.request.use(
  (config): any => {
    const needToken = (config.headers || {}).needToken === false;
    if (commonStore.token && !needToken) {
      config.headers["Authorization"] = commonStore.token;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

interface Data {
  [index: string]: unknown;
  // name:'',
  // age:''
}
interface Http {
  get(
    url: string,
    data: Data,
    config?: AxiosRequestConfig
  ): Promise<AxiosResponse>;
  post(
    url: string,
    data: Data,
    config?: AxiosRequestConfig
  ): Promise<AxiosResponse>;
  put(
    url: string,
    data: Data,
    config?: AxiosRequestConfig
  ): Promise<AxiosResponse>;
  patch(
    url: string,
    data: Data,
    config?: AxiosRequestConfig
  ): Promise<AxiosResponse>;
  delete(
    url: string,
    data: Data,
    config?: AxiosRequestConfig
  ): Promise<AxiosResponse>;
}
const http: Http = {
  get(url, data, config) {
    return instance.get(url, {
      params: data,
      ...config,
    });
  },
  post(url, data, config) {
    return instance.post(url, data, config);
  },
  put(url, data, config) {
    return instance.put(url, data, config);
  },
  patch(url, data, config) {
    return instance.patch(url, data, config);
  },
  delete(url, data, config) {
    return instance.delete(url, {
      data,
      ...config,
    });
  },
};

instance.interceptors.response.use(
  (response): any => {
    const res = response.data;
    return res;
  },
  (error) => {
    return Promise.resolve(error.response?.data);
  }
);
export default http;
